package org.ww.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ww.common.utils.PageUtils;
import org.ww.common.utils.Query;
import org.ww.product.dao.BrandDao;
import org.ww.product.entity.BrandEntity;
import org.ww.product.service.BrandService;
import org.ww.product.service.CategoryBrandRelationService;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Slf4j
@Service("brandService")
public class BrandServiceImpl extends ServiceImpl<BrandDao, BrandEntity> implements BrandService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;
    @Autowired
    private BrandDao brandDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        String key = (String) params.get("key");
        LambdaQueryWrapper<BrandEntity> wrapper = Wrappers.lambdaQuery();
        if(StringUtils.isNotBlank(key)){
            wrapper.eq(BrandEntity::getBrandId,key).or().like(BrandEntity::getName,key);
        }

        IPage<BrandEntity> page = this.page(
                new Query<BrandEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void updateDetails(BrandEntity brand) {
        this.updateById(brand);
        if(StringUtils.isNotBlank(brand.getName())){
            categoryBrandRelationService.updateBrandName(brand.getBrandId(),brand.getName());
        }
    }

    @Override
    public List<BrandEntity> selectByIds(List<Long> brandIds) {
        List<BrandEntity> brandEntities = new ArrayList<>();
        try{
            LambdaQueryWrapper<BrandEntity> wrapper = Wrappers.lambdaQuery();
            wrapper.in(BrandEntity::getBrandId,brandIds);
            brandEntities = baseMapper.selectList(wrapper);
        }catch (RuntimeException e){
            log.error("============selectByIds error===========");
        }

        if(CollectionUtils.isEmpty(brandEntities)){
            return null;
        }
        log.info("=============测试Mockito ififif=============");
        return brandEntities;
    }

}